package com.simp.utils;

import groovy.lang.*;

import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.Arrays;
import java.util.List;

/**
 * @author pan.shun
 * @since 2022/3/22 15:21
 */
public class GroovyUtils {

    /**
     * 执行Groovy脚本
     *
     * @param scriptText 脚本
     * @param function   方法名
     * @param objects    参数值
     */
    public static Object invoke(String scriptText, String function, Object... objects) {
        GroovyClassLoader classLoader = new GroovyClassLoader();
        Class groovyClass = classLoader.parseClass(scriptText);
        try {
            GroovyObject groovyObject = (GroovyObject) groovyClass.newInstance();
            return groovyObject.invokeMethod(function, objects);
        } catch (InstantiationException | IllegalAccessException e) {
            return null;
        }
    }

    /**
     * 获取脚本中参数名称
     *
     * @param scriptText     脚本内容
     * @param invokeFunction 入口函数
     */
    public static List<String> getParamsNameString(String scriptText, String invokeFunction) {
        int startIndex = invokeFunction.length() + scriptText.indexOf(invokeFunction);
        String substring = scriptText.substring(startIndex);
        String paramsString = substring.substring(substring.indexOf("(") + 1, substring.indexOf(")")).replaceAll(" ", "");
        return Arrays.asList(paramsString.split(","));
    }
}
